#!/bin/sh

TAR="tar --sort=name --mtime=@1445385600 --owner=root --group=root --numeric-owner --mode=go=rX,u+rw,a-s -cvf"

tmp=$(mktemp -d)

if [ "$#" -ne 2 ]; then
    echo "Usage: repack <url> <folder>"
    exit -1
fi

dir=`pwd`

url="$1"
filename=$(basename "$url")
folder="$2"

echo "REPACK: Repacking $filename into $folder."
echo "REPACK: Using temporary directory $tmp."

cd "$tmp"

wget --no-check-certificate "$1" ||
    (echo "REPACK: Error - couldn't download." ; exit -1)
hash1=$(sha256sum "$filename" | cut -b -64)

tar -xvf "${filename}"

${TAR} "$folder".tar "$folder" ||
    (echo "REPACK: Error - couldn't create tar." ; exit -1)
hash2=$(sha256sum "$folder".tar | cut -b -64)

mkdir -p "${dir}/dump"
mv "$folder".tar "${dir}/dump/${hash2}.tar"
cd $dir

mkdir -p pkgs
cd pkgs

echo "UPSTREAM_URL=${url}" >> "$folder".sh
echo "UPSTREAM_HASH=${hash1}" >> "$folder".sh
echo "PACK_NAME=${folder}" >> "$folder".sh
echo "PACK_HASH=${hash2}" >> "$folder".sh

echo "REPACK: Completed."
